package com.sicheng.lc.周赛.分类.哈西表or计数or滑动窗口or双指针.抵消or期待某个元素;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/6 14:54
 */
public class 还原原数组 {
    //https://leetcode.cn/problems/recover-the-original-array/
    public int[] recoverArray(int[] nums) {
        Arrays.sort(nums);
        int low = nums[0];
        int high;
        int[] res = new int[nums.length >> 1];
        HashMap<Integer, Integer> map = new HashMap<>(100);
        for (int num : nums) {
            if (num - low >= 2 && (num - low) % 2 == 0) {
                high = num;
                int index = 0;
                int k = (high - low);
                for (int x : nums) {
                    int m = map.getOrDefault(k, 0);
                    if (m == 0) {
                        map.put(x, map.getOrDefault(x, 0) + 1);
                    } else {
                        map.put(x - k, m - 1);
                        res[index++] = x - k / 2;
                    }
                }
                if (check(map)) {
                    return res;
                }
                map.clear();
            }
        }
        return null;
    }

    private boolean check(HashMap<Integer, Integer> map) {
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 0) {
                return false;
            }
        }
        return true;
    }
}
